package com.sunyard.manage.config;

import com.sunyard.dal.dto.OperatorDTO;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.dal.mapper.PopedomMapper;
import com.sunyard.entity.JWTToken;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 张昊坤
 * @Description TODO
 * @Date 2021/1/19 11:03
 */
@Service
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private OperatorMapper operatorMapper;
    @Autowired
    private PopedomMapper popedomMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("权限验证");
        String username = TokenUtil.getOpName(principalCollection.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        OperatorDTO operator = operatorMapper.getOperatorDTOByOpName(username);
        String key = "popedomList:" + operator.getRoleId();
        List<String> popedomList = null;
        popedomList = redisUtils.get(key, List.class);
        if (popedomList == null) {
            popedomList = popedomMapper.getShiroList(operator.getRoleId());
            redisUtils.set(key, popedomList);
        }
        info.addStringPermissions(popedomList);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("身份认证");
        String token = (String) authenticationToken.getCredentials();
        String username = TokenUtil.getOpName(token);
        Long currentTime = TokenUtil.getCurrentTime(token);
        //根据需要可做其他验证及异常处理
        if (username == null) {
            throw new AuthenticationException("认证失败！");
        }
        return new SimpleAuthenticationInfo(token, token, "MyRealm");
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
}

